package com.tju.resource.oauth.controller.qr;

import com.tju.resource.business.qr.ScanCodeService;
import com.tju.resource.common.ServiceException;
import com.tju.resource.result.Result;
import com.tju.resource.tool.tool.ChineseExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.Device;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

/**
 * 扫码登录
 *
 * @Author CLS
 * @Date 2022/4/1 12:31
 */
@RestController
public class QrController {

    @Autowired
    private ChineseExceptionUtils zh_ch;

    @Autowired
    private ScanCodeService codeService;

    /**
     * 第一步：获取二维码,二维码格式：设备，开始日期时间戳，有效时间（1分钟），唯一标识码
     *
     * @return
     */
    @PostMapping(value = "qr")
    public String qr(Device device) {
        return codeService.qr(device);
    }


    /**
     * 第二步：网页端轮询验证是否扫码成功
     */
    @PostMapping(value = "pollingQRCode")
    public Result<Object> pollingQRCode(@RequestBody Map<String, String> map) {
        return Optional.ofNullable(map)
                .filter(m -> m.get("qrCodeData") != null)
                .map(m -> codeService.pollingQRCode(m.get("qrCodeData")))
                .orElseThrow(() -> new ServiceException(zh_ch.MissingParameters));
    }

    /**
     * 第三步：移动端扫码验证二维码是否匹配
     *
     * @return
     */
    @PostMapping(value = "scanCodeOnMobile")
    public Result<Object> scanCodeOnMobile(@RequestBody Map<String, String> map) {
        return Optional.ofNullable(map)
                .filter(m -> m.get("qrCodeData") != null)
                .map(m -> codeService.scanCodeOnMobile(m.get("qrCodeData")))
                .orElseThrow(() -> new ServiceException(zh_ch.InvalidQRCode));
    }

    /**
     * 第四步：移动端确认网页端登录
     */
    @PostMapping(value = "confirmWebLogin")
    public Result<Object> confirmWebLogin(@RequestBody Map<String, String> map) {
        return Optional.ofNullable(map)
                .filter(m -> m.get("token") != null && m.get("qrCodeData") != null)
                .map(m -> codeService.confirmWebLogin(m.get("token"), map.get("qrCodeData")))
                .orElseThrow(() -> new ServiceException(zh_ch.MissingParameters));
    }

}
